-- 进游戏场景的入口， 根据单个游戏需求重写

local blaze = require "blaze"
local gamelib = require "club.threecard.gamelib"
local log = blaze.logging.get("entrances")

local FORBIDDEN = 403

local entrances = {}

function entrances.on_befor_enter()

end

function entrances.on_enter()

end

function entrances.on_entered()
end

function entrances.on_befor_exit()
    local app = require "app"
    local game = app.game.running
    local player = game.kbe.player()
    if not player or not player.room_api then
        log.info("无玩家登录状态，直接退出")
        return
    end

    local is_ok = false
    game.kbe.player().room_api:leave(0)
    :next(function()
        is_ok = true
        log.info("离开房间成功")
    end)
    :catch(function(errorcode)
        if errorcode == FORBIDDEN then
            log.info("离开房间失败，请求托管离开")
            return game.kbe.player().room_api:leave(1)
            :next(function()
                log.info("托管离开房间成功")
                is_ok = true
            end)
            :catch(function(errorcode)
                log.warn(string.format("托管离开房间失败：code=%s", errorcode))
                is_ok = true
            end)
        else
            log.warn(string.format("离开房间失败：code=%s", errorcode))
            error(errorcode)
        end
    end)

    while not is_ok do
        gamelib.coroutine.step()
    end
end

function entrances.on_exit()
    
end

function entrances.on_exited()
end
return entrances